package com.swotxu.firstribbonclient.customping;

import com.netflix.client.ClientFactory;
import com.netflix.client.http.HttpResponse;
import com.netflix.config.ConfigurationManager;
import com.netflix.loadbalancer.PingUrl;
import com.netflix.loadbalancer.Server;
import com.netflix.niws.client.http.RestClient;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Date: 2020/9/19 18:23
 * @Author: swotXu
 */
public class TestPingUrlConfig {

    public static void main(String[] args) throws InterruptedException, IOException {
        // 通过配置文件导入配置信息
        // ConfigurationManager.loadPropertiesFromResources("ribbon.properties");
        // 通过编码方式，设置请求的服务器
        ConfigurationManager.getConfigInstance()
                .setProperty("my-client.ribbon.listOfServers", "localhost:8081,localhost:8088");
        // 配置 ping 处理类
        ConfigurationManager.getConfigInstance()
                .setProperty("my-client.ribbon.NFLoadBalancerPingClassName", PingUrl.class.getName());
        // 配置 ping 时间间隔
        ConfigurationManager.getConfigInstance()
                .setProperty("my-client.ribbon.NFLoadBalancerPingInterval", 2);

        // 获取 REST 请求客户端
        RestClient client = (RestClient) ClientFactory.getNamedClient("my-client");
        TimeUnit.SECONDS.sleep(6);

        // 获取全部服务器
        List<Server> allServers = client.getLoadBalancer().getAllServers();
        System.out.println(allServers);

        // 输出状态
        for (Server server : allServers) {
            System.out.printf("%s 状态： %b %n", server.getHostPort(), server.isAlive());
        }
    }
}
